//
//  Shader.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 8/18/11.
//  Copyright 2011 Sinnca Studios. All rights reserved.
//

#include "shader.h"

char* openTextFile(std::string fileName)
{
	char* text;
    
    if (!fileName.empty()) {
        FILE *file = fopen(fileName.c_str(), "rt");
        
        if (file != NULL) {
            fseek(file, 0, SEEK_END);
            int count = ftell(file);
            rewind(file);
            
            if (count > 0) {
                text = (char*)malloc(sizeof(char) * (count + 1));
                count = fread(text, sizeof(char), count, file);
                text[count] = '\0';
            }
            fclose(file);
        }
    }
    return text;
}

void shader::loadShaders(std::string vs, std::string fs)
{
	
	vsText = openTextFile(vs);
	fsText = openTextFile(fs);
	
}

void shader::initShaders()
{
	vertexShader = glCreateShader(GL_VERTEX_SHADER);
	fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	
	glShaderSource(vertexShader, 1, &vsText, 0);
	glShaderSource(fragmentShader, 1, &fsText, 0);
	
	glCompileShader(vertexShader);
	glCompileShader(fragmentShader);
	
	shaderProgram = glCreateProgram();
	
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);
	
}

void shader::useShader()
{
	glUseProgram(shaderProgram);
}

void shader::unBindShader()
{
	glUseProgram(0);
}